package com.example.jpatest.service.impl;

import com.example.jpatest.dao.StudentDao;
import com.example.jpatest.entity.Student;
import com.example.jpatest.exception.REnum;
import com.example.jpatest.exception.RException;
import com.example.jpatest.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentImplService implements StudentService {

    @Autowired
    private StudentDao studentDao;

    /**
     * 查询全部
     *
     * @return
     */
    public List<Student> findAll() {
        return studentDao.findAll();
    }

    /**
     * 根据Id查询
     *
     * @param id
     * @return
     */
    public Student findById(Integer id) {
        return studentDao.findById(id).orElse(null);
    }

    /**
     * 分页查询
     *
     * @param pageable
     * @return
     */
    @Override
    public Page<Student> findAll(Pageable pageable) {
        return studentDao.findAll(pageable);
    }

    /**
     * 分页查询，有条件
     *
     * @param student
     * @param pageable
     * @return
     */
    @Override
    public Page<Student> findAll(Example<Student> student, Pageable pageable) {
        return studentDao.findAll(student, pageable);
    }

    /**
     * 根据姓名查询
     *
     * @param name
     * @return
     */
    public List<Student> findByName(String name) {
        return studentDao.findByNameLike(name);
    }


    /**
     * 插入数据
     *
     * @param student
     */
    public void insert(Student student) {
        studentDao.save(student);
    }

    /**
     * 更新操作
     *
     * @param student
     */
    public void update(Student student) {
        studentDao.save(student);
    }

    /**
     * 根据id删除
     *
     * @param id
     */
    public void delete(Integer id) {
        studentDao.deleteById(id);
    }

    /**
     * 根据姓名和密码查询
     *
     * @param name
     * @param password
     * @return
     */
    public List<Student> findByNameAndPassword(String name, String password) throws Exception {
        List<Student> byNameAndPassword = studentDao.findByNameAndPassword(name, password);
        if (byNameAndPassword.size() > 0) {
            return byNameAndPassword;
        } else {
            throw new RException(REnum.LOGIN_ERR);
        }
    }
}
